package cn.bandeqing.customer.controller;

import cn.bandeqing.base.domain.CurrentWechatMiniAppUser;
import cn.bandeqing.base.resp.Resp;
import cn.bandeqing.customer.req.BindPhoneReq;
import cn.bandeqing.customer.req.JsCodeLoginReq;
import cn.bandeqing.customer.req.SendCodeReq;
import cn.bandeqing.customer.req.WxPhoneReq;
import cn.bandeqing.customer.resp.CurrentWechatMiniAppUserResp;
import cn.bandeqing.customer.resp.JsCodeLoginResp;
import cn.bandeqing.customer.rpc.ICustomerRpc;
import cn.bandeqing.stp.StpWechatMiniAppUtil;
import cn.bandeqing.wechatminiapp.req.CustomerAddressDetailReq;
import cn.bandeqing.wechatminiapp.req.CustomerAddressSaveOrUpdateReq;
import cn.bandeqing.wechatminiapp.req.StoreDetailReq;
import cn.bandeqing.wechatminiapp.req.StoreListReq;
import cn.bandeqing.wechatminiapp.resp.CustomerAddressDetailResp;
import cn.bandeqing.wechatminiapp.resp.StoreDetailResp;
import cn.bandeqing.wechatminiapp.resp.StoreListResp;
import cn.bandeqing.wechatminiapp.rpc.IWechatMiniAppRpc;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import io.github.linpeilie.Converter;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.dromara.hutool.core.data.PhoneUtil;
import org.dromara.hutool.core.exception.ExceptionUtil;
import org.dromara.hutool.core.text.StrUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@Tag(name = "客户")
@RequestMapping("/customer")
@RestController
public class CustomerController {

    @Resource
    private WxMaService wxMaService;
    @DubboReference
    private ICustomerRpc customerRpc;
    @Resource
    private Converter converter;
    @DubboReference
    private IWechatMiniAppRpc wechatMiniAppRpc;

    @Operation(summary = "门店详情")
    @PostMapping("/storeDetail")
    public Resp<StoreDetailResp> storeDetail(@RequestBody @Valid StoreDetailReq req) {
        return wechatMiniAppRpc.storeDetail(req);
    }

    @Operation(summary = "门店列表")
    @PostMapping("/storeList")
    public Resp<List<StoreListResp>> storeList(@RequestBody @Valid StoreListReq req) {
        return wechatMiniAppRpc.storeList(req);
    }

    @Operation(summary = "地址详情")
    @PostMapping("/customerAddressDetail")
    public Resp<CustomerAddressDetailResp> customerAddressDetail(@RequestBody @Valid CustomerAddressDetailReq req) {
        return wechatMiniAppRpc.customerAddressDetail(req);
    }

    @Operation(summary = "新增或修改地址")
    @PostMapping("/customerAddressSaveOrUpdate")
    public Resp<Void> customerAddressSaveOrUpdate(@RequestBody @Valid CustomerAddressSaveOrUpdateReq req) {
        return wechatMiniAppRpc.customerAddressSaveOrUpdate(req);
    }

    @Operation(summary = "地址列表")
    @PostMapping("/addressList")
    public Resp<List<CustomerAddressDetailResp>> addressList() {
        return wechatMiniAppRpc.addressList();
    }

    @Operation(summary = "微信小程序获取手机号")
    @PostMapping("/wxPhoneBinding")
    public Resp<Void> wxPhoneBinding(@RequestBody @Valid WxPhoneReq req) {
        WxMaPhoneNumberInfo phoneNoInfo;
        try {
            phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(req.getCode());
            log.info("phoneNoInfo = {}", phoneNoInfo);
        } catch (WxErrorException e) {
            log.error("", e);
            return Resp.error(ExceptionUtil.getMessage(e));
        }
        customerRpc.wxPhoneBinding(phoneNoInfo.getPhoneNumber());
        return Resp.success();
    }

    @Operation(summary = "发送验证码")
    @PostMapping("/sendCode")
    public Resp<Void> sendCode(@RequestBody @Valid SendCodeReq req) {
        customerRpc.sendCode(req);
        return Resp.success();
    }

    @Operation(summary = "手机号绑定", description = "其实是绑定手机号")
    @PostMapping("/bindPhone")
    public Resp<Void> bindPhone(@RequestBody @Valid BindPhoneReq req) {
        customerRpc.bindPhone(req);
        return Resp.success();
    }

    @Operation(summary = "退出登录")
    @PostMapping("/logout")
    public Resp<Void> logout() {
        StpWechatMiniAppUtil.logout();
        return Resp.success();
    }

    @Operation(summary = "当前用户")
    @PostMapping("/currentUser")
    public Resp<CurrentWechatMiniAppUserResp> currentUser() {
        CurrentWechatMiniAppUser current = StpWechatMiniAppUtil.getCurrent();
        CurrentWechatMiniAppUserResp resp = converter.convert(current, CurrentWechatMiniAppUserResp.class);
        if (StrUtil.isNotBlank(resp.getCustomerPhoneNumber())) {
            String newPhone = PhoneUtil.hideBetween(resp.getCustomerPhoneNumber()).toString();
            resp.setCustomerPhoneNumber(newPhone);
        }
        return Resp.success(resp);
    }

    @Operation(summary = "jsCode 登录", description = "https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html")
    @PostMapping("/jsCodeLogin")
    public Resp<Void> jsCodeLogin(@RequestBody @Valid JsCodeLoginReq req) {
//         { "sessionKey": "GK80wiHIQvnjqyTf7ZxyAw==", "openid": "o-UGy620-kv-_d1HVkdWO2znAnc4", "unionid": null }
        WxMaJscode2SessionResult result;
        try {
            result = wxMaService.jsCode2SessionInfo(req.getJsCode());
        } catch (WxErrorException e) {
            log.error("", e);
            return Resp.error(ExceptionUtil.getMessage(e));
        }

        JsCodeLoginResp resp = customerRpc.jsCodeLogin(result.getOpenid());

        CurrentWechatMiniAppUser currentWechatMiniAppUser = converter.convert(resp, CurrentWechatMiniAppUser.class);
        StpWechatMiniAppUtil.login(currentWechatMiniAppUser);

        return Resp.success();
    }

}
